/**
 * @file 路由解析相关方法
 * */
import { RouteObject, RouterObject } from "../../index.d.js"

/** 拼接地址 */
function joinURL(...paths: string[]): string {
  let path = "/"
  paths.forEach(current => {
    if (current) {
      const isEndsWithSep = path.endsWith("/")
      const isStartsWithSep = current.startsWith("/")

      if (isStartsWithSep) path = current
      else path += isEndsWithSep ? current : `/${current}`
    }
  })

  return path
}

/** 根据路由配置, 拼接 path 解析出路由与相应的 route 列表
 *
 * @param routes 路由配置
 * @returns 由路由与对应配置组成 k-v 对象
 */
export function defineRouter(routes: RouteObject[]): RouterObject {
  const routeList = {}

  const queue = [...routes]

  while (queue.length) {
    const current = queue.shift()

    const { path, handler, children } = current as RouteObject
    const currentPath = joinURL(path)

    if (children && Array.isArray(children)) {
      children.forEach(child => {
        const { path = "/" } = child
        child.path = joinURL(currentPath, path)
      })
      queue.push(...children)
    }

    routeList[currentPath] = { path: currentPath, handler }
  }

  return routeList
}
